
package statechurn


import primitives.graph.*;
import translator.DOTWriter;
import java.io.File;

/**
 *
 * @author mat
 */
class PTAMaker {
		/**
	*
	* FORMAT:
	* [passive]
	* k #NUM
	* [dotoutput]
	* #TRACE
	* 
	* 
	* #NUM : 0-9#NUM | ""
	* #TRACE : (+|-) #CALLS \n
	* #CALLS : "" | "[A-Za-z.0-9_] #CALLS"
	*/
	def nodes = [:]
	int counter = 0;
	
	def static K_RE = ~/k\s+(\d+)/;
	def static TRACE = ~/^(\+|-)/;
	

	
	int k = 5;



	
	def static processTrace(ins){
		for(def i=0; i<ins.length(); i++){
			if(ins.charAt(i) == '+' || ins.charAt(i) == '-'){
				ins= ins.substring(i+1);
				break;
			}
		}

		return ins.tokenize();
	}
	
	def get(){
		def n = new Node("GEN$counter");
		nodes["GEN$counter"] = n;

		
		counter++;
		return n
	}
	
	void connect(name1, name2, label){
		def node1 = get(name1)
		def node2 = get(name2)
		
		node1.connect(node2,label);
		
	}
	
	void pathTo(traces, fromNode){
		def current = fromNode;
		
		def found = false;
		
		while(!traces.isEmpty()){
			def label = traces.pop();
			//print "processing $label "
			def newCurrent = null
			current.transitionsAsT.each{
				if(it.getLabel().equals(label)){
					newCurrent = it.getDestinationNode();
				}
			}
			if(newCurrent == null){
				def newNode = get();
				current.connect(newNode, label);
				current = newNode;
			}else{
				current.connect(newCurrent, label);
				current = newCurrent;
			}

		}
		
	}


	
	
	Graph g = new Graph();





	public Graph getGraph(){
		Graph g = new Graph();
		for(String k : nodes.keySet()){
			Node n = nodes.get(k);
			g.addNode(n);
		}
		return g;
	}
	
	
	public loadPTAFromTraces(String[] lines){
		def kstmt = lines.find{(K_RE.matcher(it).matches())} 
		def knum = kstmt =~ K_RE
		k =  knum[0][1].toInteger()
                
		def start = new Node("Start");
		nodes['Start'] = start;
		def LOTS = 50000000;
		start.refCount = LOTS;
		def traces = getTraces(lines)
		
		traces.each{
			traceLine -> 
			pathTo(traceLine, start);
		}
 

		return nodes;
	}

	
	def loadPTAFromTraces(File input) throws IOException{
			return loadPTAFromTraces((String[])(input.readLines().toArray()))
	}
	
	def static getTraces(String[] lines){
		def traces = lines.findAll{it =~ TRACE};
		def ret = traces.collect{
			processTrace(it).reverse()
		}
		return ret;		
		
	}
	
	public static void main(String[] args){
		if(args.length > 0 && args[0].equalsIgnoreCase("TestEq")){
			testTracesOf();
			System.exit(1);
		}
		def tp = new TraceParser()
		tp.loadPTAFromTraces(new File(args[0]));
		
		def g = tp.doKTails()
		//println new DOTWriter().getRepresentation(g);
		

	}
	
	public dbg(msg){
		if(debug) println "DEBUG: $msg"
	}
	public dbgp(msg){
		if(debug)println msg
	}
}

